//
//  DAUEngineRoomTVC.m
//  DAU-iOS
//
//  Created by XiangDongMBP on 2016/11/17.
//  Copyright © 2016年 East. All rights reserved.
//

#import "DAUEngineRoomTVC.h"
#import "DAUPerCenterTVC.h"
#import <MJRefresh.h>
#import "DAUEnginResultsTVC.h"
#import "DAUMonDetailVC.h"

@interface DAUEngineRoomTVC ()<UISearchResultsUpdating, UISearchBarDelegate>

@property (strong, nonatomic) IBOutlet UIView *tHeaderBgView;
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) DAUEnginResultsTVC *resultsTableController;
@property (readonly, nonatomic) DAUEngineRoomModel *model;

@end

static NSInteger const kPageSize = 15;  //!< 每次请求的记录数

@implementation DAUEngineRoomTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
//     self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (DAUEngineRoomModel *)model {
    return DAU_APP_DELEGATE.dauModel.engineRoom;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initNavigationBar {
    self.navigationItem.title = NSLocalizedString(@"机房", nil);
}

- (void)initSubViews {
    // UISearchController
    self.resultsTableController = [[DAUEnginResultsTVC alloc] init];
    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
    //    searchController.delegate = self;                             s//设置UISearchControllerDelegate协议代理
    searchController.searchResultsUpdater = self;                   //设置UISearchResultsUpdating协议代理
    searchController.dimsBackgroundDuringPresentation = YES;        //是否添加半透明覆盖层(主要用于有新的结果显示controller，类似短信APP)
    searchController.hidesNavigationBarDuringPresentation = YES;    //是否隐藏导航栏
    searchController.searchBar.delegate = self;
    searchController.searchBar.placeholder = NSLocalizedString(@"请输入机房名称", nil);
    [searchController.searchBar sizeToFit];
    self.searchController = searchController;
    self.definesPresentationContext = YES;
    
    // we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
    self.resultsTableController.tableView.delegate = self;
    
    [self.tHeaderBgView addSubview:self.searchController.searchBar];
    self.tableView.tableHeaderView = self.tHeaderBgView;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉、上拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - <UITableViewDelegate>代理
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DAUEngineRoomItem *item = (tableView == self.tableView) ? self.model.result[indexPath.row] : DAU_APP_DELEGATE.dauModel.engineSeaResult.result[indexPath.row];
    
    DAUMonDetailVC *vc = [[DAUMonDetailVC alloc] init];
    vc.collectorId = item.collectorId;
    vc.collectorName = item.name;
    [self.navigationController pushViewController:vc animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.result.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
    if (indexPath.row < self.model.result.count) {
        [self configureCell:cell forProduct:self.model.result[indexPath.row]];
    }
    return cell;
}

#pragma mark - <UISearchResultsUpdating>代理
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = searchController.searchBar.text;
    NSLog(@"输入的搜索词语是%@", searchString);
    
    // hand over the filtered results to our search results table
    DAUEnginResultsTVC *tableController = (DAUEnginResultsTVC *)self.searchController.searchResultsController;
    tableController.keywords = searchString;
    [tableController refreshNewData];
}

#pragma mark -<UISearchBarDelegate>代理
//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//    NSString *searchString = searchBar.text;
//    NSLog(@"输入的搜索词语是%@", searchString);
//    
//    // hand over the filtered results to our search results table
//    DAUEnginResultsTVC *tableController = (DAUEnginResultsTVC *)self.searchController.searchResultsController;
//    tableController.keywords = searchString;
//    [tableController refreshNewData];
//}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    // 清空全局保存的数据和界面上保存的数据
    DAU_APP_DELEGATE.dauModel.engineSeaResult = nil;
    DAUEnginResultsTVC *tableController = (DAUEnginResultsTVC *)self.searchController.searchResultsController;
    tableController.keywords = @"";
    [tableController.tableView reloadData];
}

#pragma mark - 网络请求
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    NSInteger startIndex = isHeader ? 0 : DAU_APP_DELEGATE.dauModel.engineRoom.result.count;
    NSString *urlStr = [DAUUrlProtocolMerger apiCollectorList];
    NSDictionary *pars = @{@"page"   : @(startIndex),
                           @"size"   : @(kPageSize),
                           @"keyword": @""};
    
    [XDAFHttpRequest GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求机房列表返回 %@", responseObject);
        if ([responseObject[@"errCode"] integerValue] == 200) {
            DAUEngineRoomModel *temp = [DAUEngineRoomModel yy_modelWithJSON:responseObject];
            if (isHeader || !DAU_APP_DELEGATE.dauModel.engineRoom) {
                DAU_APP_DELEGATE.dauModel.engineRoom = temp;
            } else {
                [DAU_APP_DELEGATE.dauModel.engineRoom addMoreWithData:temp];
            }
            [self tableViewEndRefresh:isHeader withMoreData:temp.result.count];
            [self.tableView reloadData];
        } else {
            [self tableViewEndRefresh:isHeader withMoreData:YES];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"result"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求机房列表失败 %@", error);
        [self tableViewEndRefresh:isHeader withMoreData:YES];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"网络请求失败", nil)];
    }];
}

- (void)tableViewEndRefresh:(BOOL)isHeader withMoreData:(BOOL)more {
    if (isHeader) {
        [self.tableView.mj_footer resetNoMoreData];
        [self.tableView.mj_header endRefreshing];
    } else {
        if (more) {
            [self.tableView.mj_footer resetNoMoreData];
            [self.tableView.mj_footer endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
}

@end
